package com.snails.net.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * 网络信息
 * @author lawrence
 * @date   2019-04-04
 */

public final class NetworkUtil {
    private static volatile NetworkUtil instance = null;
    private static Context ctx = null;
    private ConnectivityManager manager = null;

    public static void init(Context ctx) {
        if (NetworkUtil.ctx == null) {
            NetworkUtil.ctx = ctx.getApplicationContext();
        }
    }

    public static Context getCtx() {
        return NetworkUtil.ctx;
    }

    public static NetworkUtil instance() {
        if (instance == null) {
            synchronized (NetworkUtil.class) {
                if (instance == null) {
                    checkInit();
                    instance = new NetworkUtil(NetworkUtil.ctx);
                }
            }
        }
        return instance;
    }

    // ================================================================================
    // --- ---
    // ================================================================================
    private NetworkUtil(Context ctx) {
        manager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    private static void checkInit() {
        if (NetworkUtil.ctx == null) {
            throw new NullPointerException("请先调用【NetworkUtil.init()】进行初始化。");
        }
    }

    private ConnectivityManager manager() {
        if (manager == null) {
            synchronized (NetworkUtil.class) {
                if (manager == null) {
                    checkInit();
                    manager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
                }
            }
        }
        return manager;
    }

    // ================================================================================
    // --- ---
    // ================================================================================
    /**
     * 网络连接状态
     * @return true-已连接，false-未连接
     */
    public boolean isConnected() {
        if (manager() != null) {
            NetworkInfo info = manager().getActiveNetworkInfo();
            if (info != null && info.isConnected()) return info.isConnected();
        }
        return false;
    }

}
